package com.jt.config;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 金帮嘉诚 @date 2021-08-24 星期二 15:46
 * 自定义过滤器 全局
 */
@Component
public class AuthGatewayFilter implements GlobalFilter, Ordered {

    @Value("${white.prefix:/nacos}")
    private String whitePrefix;
    /**你的业务可以写到这个filter方法内部
     * @param exchange 基于此对象可以获取请求和响应对象
     * @param chain 这个对象指向了一个过滤链(这个链中有多个过滤器)
     * */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        System.out.println("path = " + path);

        if (!path.startsWith(whitePrefix)) {
            System.out.println("路径错误,前缀不是"+whitePrefix);
//            return response.setComplete();//直接结束
            //响应内容到客户端
//            String content = "request failure";
            //或者 写json
            Map<String,Object> map = new HashMap<>();
            map.put("message","request failure");
            map.put("status","502");
            String content = new Gson().toJson(map);
            //......
            byte[] bytes = content.getBytes();
            DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(dataBuffer));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
